<template>
    <el-container>
      <el-aside width="200px">
        <el-menu :default-active="activeChapter" @select="handleSelect">
          <el-menu-item v-for="chapter in chapters" :key="chapter.idchapter" :index="chapter.idchapter.toString()">
            {{ chapter.chapName }}
          </el-menu-item>
        </el-menu>
      </el-aside>
  
      <el-main>
        <el-card>
          <div v-html="currentChapterContent"></div>
        </el-card>
      </el-main>
  
      <el-aside width="300px">
        <el-card>
          <h3>{{ book.bookName }}</h3>
          <p>作者: {{ book.penName }}</p>
          <p>点击量: {{ book.clicks }}</p>
          <el-slider v-model="rating" :min="0" :max="100" show-input></el-slider>
          <el-button type="primary" @click="submitRating">提交评分</el-button>
          <el-button type="primary" @click="toggleBookshelf">{{ isInBookshelf ? '移出书架' : '加入书架' }}</el-button>
        </el-card>
      </el-aside>
    </el-container>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        book: {},
        chapters: [],
        currentChapterContent: '',
        activeChapter: '',
        rating: 0,
        isInBookshelf: false
      };
    },
    created() {
      const idbook = this.$route.params.idbook;
      this.fetchBook(idbook);
      this.fetchChapters(idbook);
      this.incrementClicks(idbook);
      this.checkBookshelf(idbook);
    },
    methods: {
      fetchBook(idbook) {
        axios.get(`/api/books/${idbook}`)
          .then(response => {
            this.book = response.data;
          })
          .catch(error => {
            console.error('获取书籍信息失败:', error);
          });
      },
      fetchChapters(idbook) {
        axios.get(`/api/books/${idbook}/chapters`)
          .then(response => {
            this.chapters = response.data;
            if (this.chapters.length > 0) {
              this.activeChapter = this.chapters[0].idchapter.toString();
              this.fetchChapterContent(this.activeChapter);
            }
          })
          .catch(error => {
            console.error('获取章节列表失败:', error);
          });
      },
      fetchChapterContent(idchapter) {
        axios.get(`/api/chapters/${idchapter}`)
          .then(response => {
            this.currentChapterContent = response.data.content;
          })
          .catch(error => {
            console.error('获取章节内容失败:', error);
          });
      },
      handleSelect(idchapter) {
        this.activeChapter = idchapter;
        this.fetchChapterContent(idchapter);
      },
      async submitRating() {
        try {
          const token = localStorage.getItem('accessToken');
          await axios.post(`/api/books/${this.book.idbook}/rating`, { userRating: this.rating }, {
            headers: {
              Authorization: `Bearer ${token}`
            }
          });
          this.$message.success('评分提交成功');
        } catch (error) {
          console.error('提交评分失败:', error);
          this.$message.error('评分提交失败');
        }
      },
      async toggleBookshelf() {
        try {
          const token = localStorage.getItem('accessToken');
          const userResponse = await axios.get('/api/users/me', {
            headers: { Authorization: `Bearer ${token}` }
          });
          const iduser = userResponse.data.iduser;
          const action = this.isInBookshelf ? 'delete' : 'post';
          const url = this.isInBookshelf ? `/api/bookshelf?iduser=${iduser}&idbook=${this.book.idbook}` : '/api/bookshelf';
          const data = this.isInBookshelf ? {} : { iduser, idbook: this.book.idbook };
  
          await axios({
            method: action,
            url: url,
            data: data,
            headers: {
              Authorization: `Bearer ${token}`
            }
          });
          this.isInBookshelf = !this.isInBookshelf;
          this.$message.success(this.isInBookshelf ? '已加入书架' : '已移出书架');
        } catch (error) {
          console.error('操作书架失败:', error);
          this.$message.error('操作书架失败');
        }
      },
      incrementClicks(idbook) {
        axios.post(`/api/books/${idbook}/click`)
          .then(response => {
            console.log('点击量增加成功');
          })
          .catch(error => {
            console.error('点击量增加失败:', error);
          });
      },
      async checkBookshelf(idbook) {
        try {
          const token = localStorage.getItem('accessToken');
          const userResponse = await axios.get('/api/users/me', {
            headers: { Authorization: `Bearer ${token}` }
          });
          const iduser = userResponse.data.iduser;
  
          const response = await axios.get(`/api/bookshelf/${iduser}`, {
            headers: { Authorization: `Bearer ${token}` }
          });
          const bookshelf = response.data;
          this.isInBookshelf = bookshelf.some(item => item.idbook === idbook);
        } catch (error) {
          console.error('检查书架失败:', error);
        }
      }
    }
  };
  </script>
  
  <style scoped>
  body {
    background-color: #e6ffe6; /* 浅绿色背景 */
    font-family: 'Microsoft YaHei', sans-serif; /* 微软雅黑字体 */
  }
  
  .header {
    background-color: #218838;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 60px;
    font-size: 24px;
    border-bottom: none;
  }
  
  .main {
    padding: 20px;
  }
  
  .el-button {
    margin-top: 10px;
  }
  
  h3 {
    cursor: pointer;
    color: #28a745; /* 绿色 */
  }
  h3:hover {
    text-decoration: underline;
  }
  </style>
  